package com.example.wechatpyq;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Browser;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wechatpyq.view.CustomDialog;
import com.wcl.notchfit.NotchFit;
import com.wcl.notchfit.args.NotchProperty;
import com.wcl.notchfit.args.NotchScreenType;
import com.wcl.notchfit.core.OnNotchCallBack;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static com.wcl.notchfit.utils.SizeUtils.getScreenWidth;


public class PYQActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView img_backgound,img_camere;
    private RelativeLayout rel_img_top_btn;
    private String neirong;
    private Bitmap tupian;
    private ListView lv;
    private List<JavaBean> list=new ArrayList();
    private SharedPreferences sharedPreferences;
    private static final int READSP=100;
    private CustomDialog customDialog;

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case READSP:
                    List reverlist=new ArrayList();
                    reverlist.clear();
                    reverlist.addAll(list);
                    Collections.reverse(reverlist);
                    MyAdapter myAdapter=new MyAdapter(reverlist);
                    lv.setAdapter(myAdapter);
                    setListViewHeightBasedOnChildren(lv);
                    customDialog.dismiss();//消失
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pyq);
        init();
        initScreen(this);

        sharedPreferences=getSharedPreferences("pyq",MODE_PRIVATE);

        if (!sharedPreferences.getString("pyqinfo", "nulls").equals("nulls")) {
            //加载动画
            customDialog = new CustomDialog(this, "正在加载...");
            customDialog.show();//显示,显示时页面不可点击,只能点击返回
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                String pyqinfostr = sharedPreferences.getString("pyqinfo", "nulls");
                if (!pyqinfostr.equals("nulls")){
                    list.clear();
                    try {
                        JSONArray jsonArray=new JSONArray(pyqinfostr);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            String text = jsonObject.getString("text");
                            String bitmapstr = jsonObject.getString("bitmap");
                            Bitmap bitmap = stringToBitmap(bitmapstr);
                            JavaBean javaBean=new JavaBean(text,bitmap);
                            list.add(javaBean);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    handler.sendEmptyMessage(READSP);
                }
            }
        }).start();
    }

    /**
     * String转回bitmap
     * @param string
     * @return
     */
    public static Bitmap stringToBitmap(String string) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    /**
     * 图片转成string
     *
     * @param bitmap
     * @return
     */
    public static String convertIconToString(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] appicon = baos.toByteArray();// 转为byte数组 return
        String s = Base64.encodeToString(appicon, Base64.DEFAULT);
        return s;
    }

    private void init() {
        img_backgound=findViewById(R.id.img_background);
        rel_img_top_btn=findViewById(R.id.rel_img_top_btn);
        img_camere=findViewById(R.id.img_camere);
        img_camere.setOnClickListener(this);
        lv=findViewById(R.id.lv);
    }

    /**
     * 打开本地相册选择图片
     */
    private void selectPic(){
        //intent可以应用于广播和发起意图，其中属性有：ComponentName,action,data等
        Intent intent=new Intent();
        intent.setType("image/*");
        //action表示intent的类型，可以是查看、删除、发布或其他情况；我们选择ACTION_GET_CONTENT，系统可以根据Type类型来调用系统程序选择Type
        //类型的内容给你选择
        intent.setAction(Intent.ACTION_GET_CONTENT);
        //如果第二个参数大于或等于0，那么当用户操作完成后会返回到本程序的onActivityResult方法
        startActivityForResult(intent, 1);
    }
    /**
     *把用户选择的图片显示在imageview中
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //用户操作完成，结果码返回是-1，即RESULT_OK
        if(resultCode==RESULT_OK){
            //获取选中文件的定位符
            Uri uri = data.getData();
            Log.e("uri", uri.toString());
            //使用content的接口
            ContentResolver cr = this.getContentResolver();
            try {
                //获取图片
                Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                tupian=bitmap;
                JavaBean javaBean=new JavaBean(neirong,tupian);
                list.add(javaBean);
                List reverlist=new ArrayList();
                reverlist.clear();
                reverlist.addAll(list);
                Collections.reverse(reverlist);
                MyAdapter myAdapter=new MyAdapter(reverlist);
                lv.setAdapter(myAdapter);
                show.cancel();
                setListViewHeightBasedOnChildren(lv);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //存储数据
                        JSONArray jsonArray=new JSONArray();
                        for (int i = 0; i < list.size(); i++) {
                            String bitmapstr = convertIconToString(list.get(i).getBitmap());
                            String text = list.get(i).getText();
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("text", text);
                                jsonObject.put("bitmap",bitmapstr);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            jsonArray.put(jsonObject);
                        }
                        SharedPreferences.Editor edit = sharedPreferences.edit();
                        edit.putString("pyqinfo", String.valueOf(jsonArray));
                        edit.commit();
                    }
                }).start();
            } catch (Exception e) {
                Log.e("Exception", e.getMessage(),e);
            }
        }else{
            //操作错误或没有选择图片
            Log.i("MainActivtiy", "operation error");
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initScreen(final Activity activity) {//刘海屏适配
        NotchFit.fit(activity, NotchScreenType.TRANSLUCENT, new OnNotchCallBack() {//沉浸式状态栏
            @Override
            public void onNotchReady(NotchProperty notchProperty) {
                if(notchProperty.isNotchEnable()){
                    //判断横竖屏
                    if (activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
                        // 横屏
                        int notchHeight = notchProperty.getNotchWidth();
                        ViewGroup.LayoutParams layoutParams = rel_img_top_btn.getLayoutParams();
                        layoutParams.height=rel_img_top_btn.getHeight()+ notchHeight;
                        rel_img_top_btn.setLayoutParams(layoutParams);
//                        Toast.makeText(getApplicationContext(), "横"+notchHeight, Toast.LENGTH_SHORT).show();
                    } else if (activity.getResources().getConfiguration().orientation ==Configuration.ORIENTATION_PORTRAIT) {
                        // 竖屏
                        int notchHeight = notchProperty.getNotchHeight();
//                        int measuredHeight = rel_img_top_btn.getMeasuredHeight();
                        ViewGroup.LayoutParams layoutParams = rel_img_top_btn.getLayoutParams();
                        layoutParams.height=rel_img_top_btn.getHeight()+ notchHeight;
                        rel_img_top_btn.setLayoutParams(layoutParams);
//                        Toast.makeText(getApplicationContext(), "竖"+notchHeight, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }
    AlertDialog show;
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.img_camere:
                View alertView = getLayoutInflater().inflate(R.layout.item_alert, null, false);
                AlertDialog.Builder builder = new AlertDialog.Builder(PYQActivity.this);
                builder.setView(alertView);
                final EditText et =alertView.findViewById(R.id.alert_et);
                Button btn=alertView.findViewById(R.id.alert_btn);
                show = builder.show();
                show.setCanceledOnTouchOutside(false);
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (et.getText().toString().isEmpty()) {
                            Toast.makeText(PYQActivity.this, "请不要为空", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        String text = et.getText().toString();//文本内容
                        //选择图片
                        selectPic();
                        neirong=text;
                    }
                });
                break;
        }
    }

    private class MyAdapter extends BaseAdapter{
        private List<JavaBean> mData;

        public MyAdapter(List<JavaBean> mData) {
            this.mData = mData;
        }

        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int i) {
            return mData.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder holder=null;
            if (view == null) {
                view= getLayoutInflater().inflate(R.layout.item_lv, null);
                holder=new ViewHolder();
                holder.img=view.findViewById(R.id.item_img_guanggao01);
                holder.tv_name=view.findViewById(R.id.item_tv_name);
                holder.tv_neirong=view.findViewById(R.id.item_tv_text01);
                holder.tv_pinglun=view.findViewById(R.id.item_tv_text02);
                view.setTag(holder);
            }else {
                holder= (ViewHolder) view.getTag();
            }
            holder.tv_neirong.setText(""+mData.get(i).getText());
            setspaint(holder.tv_neirong,false);
            holder.tv_pinglun.setText("涂鸦："+mData.get(i).getText());
            setspaint(holder.tv_pinglun,true);

            int screenWidth = getScreenWidth(PYQActivity.this); // 获取屏幕宽度
            ViewGroup.LayoutParams lp = holder.img.getLayoutParams();
            lp.width = screenWidth;
            lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            holder.img.setLayoutParams(lp);

            holder.img.setMaxWidth(screenWidth);
            holder.img.setMaxHeight(screenWidth * 5); //这里其实可以根据需求而定，我这里测试为最大宽度的5倍

            holder.img.setImageBitmap(mData.get(i).getBitmap());
            return view;
        }

        /**
         *
         * @param tv
         * @param Colorname  true则是涂鸦：两个字变色， false则不变色
         */
        private void setspaint(TextView tv,boolean Colorname) {
            String s = tv.getText().toString();
            String name="涂鸦";
            SpannableStringBuilder style=new SpannableStringBuilder(s);
            if (Colorname) {
                style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorname)),0,name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                style.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
//            style.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            //这句很重要，也可以添加自定义正则表达式
            Linkify.addLinks(style,Linkify.ALL);
            //主要是获取span的位置
            URLSpan[] spans = style.getSpans(0, s.length(), URLSpan.class);
            if (!(spans.length < 0||spans.length==0)) {//添加非空判断
                URLSpanNoUnderline urlSpanNoUnderline = new URLSpanNoUnderline(spans[0].getURL());//需要添加判断
                //这里可以用过循环处理就可以动态实现文本颜色的差别化了
                //设置高亮样式一
                int spanStart = style.getSpanStart(spans[0]);
                int spanEnd = style.getSpanEnd(spans[0]);
//              style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorname)), spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                style.setSpan(urlSpanNoUnderline, spanStart, spanEnd, 0);
            }
            tv.setText(style);
        }

        private class ViewHolder{
            private TextView tv_name,tv_neirong,tv_pinglun;
            private ImageView img;
        }


        public class URLSpanNoUnderline extends ClickableSpan {
            private final String mURL;
            public URLSpanNoUnderline(String url) {
                mURL = url;
            }

            public String getURL() {
                return mURL;
            }

            @Override

            public void onClick(View widget) {
                Uri uri = (Uri) widget.getTag();
                if(uri!=null) {
                    final Context context = widget.getContext();
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
                    context.startActivity(intent);
                }

            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
                ds.setColor(getResources().getColor(R.color.colorname));
                //指定文字颜色
//            ds.setTextSize(Color.parseColor("#00ffff"));
            }
        }
    }
    private class JavaBean {
        private String text;//文本内容
        private Bitmap bitmap;//图片  image.setImageBitmap(bitmap);

        public JavaBean(String text, Bitmap bitmap) {
            this.text = text;
            this.bitmap = bitmap;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public Bitmap getBitmap() {
            return bitmap;
        }

        public void setBitmap(Bitmap bitmap) {
            this.bitmap = bitmap;
        }
    }
    /**
     *避免listview在scroll布局中只显示第一条item
     */
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }
}
